package xyz.naokeziteng.leetcode;

import xyz.naokeziteng.data_structure.heap.MaxHeap;

import java.util.Arrays;

/**
 * @author hawk
 * @date 2022/9/14
 * @desc
 **/
public class FindKthSmall {

    public static int[] findKthSmall(int[] data, int k) {
        MaxHeap<Integer> queue = new MaxHeap<>(data.length);
        for (int i = 0; i < k; i++) {
            queue.add(data[i]);
        }
        for (int i = k; i < data.length; i++) {
            if (!queue.isEmpty() && queue.findMax() > data[i]) {
                queue.poll();
                queue.add(data[i]);
            }
        }
        int[] result = new int[k];
        for (int i = 0; i < result.length; i++) {
            result[i] = queue.poll();
        }
        return result;
    }

    public static void main(String[] args) {
        int[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int[] result = findKthSmall(data, 8);
        System.out.println(Arrays.toString(result));
    }
}
